<?php
/**
 * Created by PhpStorm.
 * User: bxm
 * Date: 2022/6/24
 * Time: 13:13
 */

namespace app\api\controller\worker;


use app\api\controller\Base;
use app\common\model\AdminModel;
use app\common\model\node\NodeModel;
use app\common\model\node\NodeProcessModel;
use app\common\model\worker\CustomerAuthModel;
use app\common\model\worker\CustomerBudgetDetailModel;
use app\common\model\worker\CustomerBudgetModel;
use app\common\model\worker\CustomerGoodsDataModel;
use app\common\model\worker\CustomerModel;
use app\common\model\worker\CustomerRulerModel;
use app\common\model\worker\RecommendModel;
use app\common\model\worker\TaskModel;
use think\facade\Db;
use think\Request;
use think\Validate;

class CustomerBudgetController extends Base
{
    private $model;
    private $customerModel;
    private $customerBudgetDetailModel;
    private $nodeModel;
    private $taskModel;
    private $adminModel;
    /**
     * 构造方法
     * @access public
     * @throws \Exception
     */
    public function __construct()
    {

        parent::__construct();
        $this->checkLogin();
        $this->model = new CustomerBudgetModel();
        $this->customerBudgetDetailModel = new CustomerBudgetDetailModel();
        $this->customerModel = new CustomerModel();
        $this->nodeModel = new NodeModel();
        $this->taskModel = new TaskModel();
        $this->adminModel = new AdminModel();

    }
    //预算记录
    public function list(Request $request){
        $param = $request->param();
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d') ?? 1; //当前页
        $type_id       = $this->request->param('type_id/d');
        $keyword    = $this->request->param('keyword')?? '';
        //开始校验
        $this->validate($param,[
            'customer_id|客户id'=>'require',

        ]);

        $where = [];
        $where[] = ['cb.customer_id', '=', $param['customer_id']];
        if($keyword){
            $where[] = ['cal.goods_name', 'like', '%'.$keyword.'%'];
        }
        $list = CustomerBudgetDetailModel::alias('cal')

            ->leftJoin('admin a', 'a.id = cal.action_admin_id')
            ->leftJoin('customer_budget cb', 'cb.id = cal.budget_id')
            ->where($where)
            ->order('cal.id','desc')
            ->field('a.nickname,cal.*')
             ->paginate(['list_rows'=> $pageSize, 'page' => $pageNumber]);

        $this->result($list,'操作成功',1);
    }
    //添加预算
    public function add(Request $request){
        $roles_ids = $this->role_ids;
        if(!in_array(7,$roles_ids)){
            exception('该用户没有权限，只有业务员有操作权限！');
        }
        //$parms = $request->all();
        $param = $request->param();
        //开始校验
        $this->validate($param,[
            'customer_id|客户id'=>'require',
            'goods_data_id|商品id'=>'require',
            'goods_name|商品名称'=>'require',
            'budget_amount|客户预算价'=>'require',
            'finish_time|要求完成时间'=> 'require',
            'admin_id|客户代表' => 'require',

        ]);
        $data = [
            'customer_id' => $param['customer_id'],
            'goods_name' => $param['goods_name'],
            'goods_data_id' => $param['goods_data_id'],
            'budget_amount' => $param['budget_amount'],
            'finish_time' => $param['finish_time'],
            'admin_id' =>$param['admin_id'],
            'remark' =>$param['remark'] ?? '',
            'action_admin_id' =>$this->loginInfo['id'],

        ];
        //判断是否已预算
        $info = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->value('budget_id');
        if($info['budget_id']){

            $this->result([],'该客户下的该商品已申请预算，请勿重复操作！',0);
        }
        if($info['budget_status'] == 1){

            $this->result([],'该客户下的该商品已预算，请勿重复操作!',0);
        }
        Db::startTrans();
        $info = $this->model->add($data);
        if(!$info){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        //申请后进入待预算状态
        $result = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->update(['budget_id'=>$info['id']]);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        $nodeProcess = NodeProcessModel::where('node_id', 6)->order('id', 'asc')->find();

        $dataTask = [
            'customer_id' => $data['customer_id'],
            'order_id' => 0,
            'node_id' => 6,
            'process_id' => $nodeProcess['id'],
            'receive_admin_id' => $nodeProcess['audit_admin_id'],
            'action_table_id'=>$info['id'],//操作表id
            'admin_id'=>$this->loginInfo['id'],
        ];
        $result = $this->taskModel->commonAddTask($dataTask);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        Db::commit();
        $this->taskModel->sendTaskInfo($dataTask['receive_admin_id'],$nodeProcess['process_name']);
        $this->result($info,'操作成功',1);

    }
    //完成预算
    public function finishBudgetEdit(Request $request){
        $roles_ids = $this->role_ids;
       if(!in_array(8,$roles_ids)){

           $this->result([], "该用户没有权限，只有客户代表有操作权限！", 0);
       }

        $param = $request->param();
        //开始校验
        $this->validate($param,[
            'customer_id|客户id'=>'require',
            'goods_name|商品名称'=>'require',
            'goods_data_id|商品id'=>'require',
            'retail_price|零售价'=> 'require',
            'discount_price|折扣价格' => 'require',
            'final_price|折扣报价' => 'require',
            //'detail_imgs|预算明细照片'=> 'require',
        ]);

        $customerGoodsDataInfo = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->find();
        if($customerGoodsDataInfo['budget_status'] == 1){

            $this->result([], "预算已完成，请勿重复操作！！！", 0);

        }
        if($customerGoodsDataInfo['budget_status'] !=0 ){


            $this->result([], "该客户下的该商品不是待预算状态，请勿重复操作！！", 0);

        }

        $data = [
            'budget_id' => $customerGoodsDataInfo['budget_id'],
            'retail_price' => $param['retail_price'],
            'discount_price' => $param['discount_price'],
            'final_price' => $param['final_price'],
            'detail_imgs' => $param['detail_imgs'] ? json_encode($param['detail_imgs'],JSON_UNESCAPED_UNICODE) : '',
            'remark' => $param['final_remark'] ?? '',
            'action_admin_id' =>$this->loginInfo['id'],
        ];


        Db::startTrans();
        $result = $this->customerBudgetDetailModel->add($data);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        //完成预算才算师以预算
        $result = CustomerGoodsDataModel::where('id',$param['goods_data_id'])->update(['budget_detail_id'=>$result['id'],'budget_status'=>1]);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        $result = CustomerModel::where('id', $param['customer_id'])->inc('budget_amount',$param['final_price'])->update();
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        Db::commit();
        $this->result($result,'操作成功',1);
    }
    //修改预算
    public function edit(Request $request){
        $roles_ids = $this->role_ids;
        if(!in_array(8,$roles_ids)){

            $this->result([], "该用户没有权限，只有客户代表有操作权限！！！！", 0);
        }

        $param = $request->param();
        //开始校验
        $this->validate($param,[
            'budget_id|预算id'=>'require',
            'customer_id|客户id'=>'require',
            'goods_name|商品名称'=>'require',
            'goods_data_id|商品id'=>'require',
            'retail_price|零售价'=> 'require',
            'discount_price|折扣价格' => 'require',
            'final_price|折扣报价' => 'require',
            'detail_imgs|预算明细照片'=> 'require',
        ]);

        $info = CustomerGoodsDataModel::where('goods_data_id',$param['goods_data_id'])->find();
        if($info['budget_status'] != 1){

            $this->result([], "该客户下的该商品不是已预算，请耐心等待！", 0);
        }
        $data = [
            'budget_id' => $param['budget_id'],
            'retail_price' => $param['retail_price'],
            'discount_price' => $param['discount_price'],
            'final_price' => $param['final_price'],
            'detail_imgs' => json_encode($param['detail_imgs'],JSON_UNESCAPED_UNICODE),
            'remark' => $param['final_remark'] ?? '',
        ];

//        $info_detail = $this->customerBudgetDetailModel->where('budget_id',$param['budget_id'])->find();
//        if(!$info_detail){
//            exception('预算还未完成，完成预算才可修改！');
//        }
        $customerBudgetDetailInfo = $this->customerBudgetDetailModel->where('id',$info['budget_detail_id'])->find();

        $val =   $param['final_price'] - $customerBudgetDetailInfo['final_price'];
        Db::startTrans();
        $result = $this->customerBudgetDetailModel->where('id',$info['budget_detail_id'])->update($data);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }


        if($val >0){
            $result = CustomerModel::where('id', $param['customer_id'])->inc('budget_amount',$val)->update();
        }else{
            $result = CustomerModel::where('id', $param['customer_id'])->dec('budget_amount',$val)->update();
        }
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        Db::commit();
        $this->result($result,'操作成功',1);
    }
    public function getInfo(Request $request)
    {
        $param = $request->param();
        //开始校验
        $this->validate($param,[
            'id|记录id'=>'require',
        ]);
        $id = $param['id'];
        $list = CustomerBudgetDetailModel::alias('cal')
            ->leftJoin('admin a', 'a.id = cal.action_admin_id')
            ->leftJoin('customer_budget cb', 'cb.id = cal.budget_id')
            ->where('cal.id',$id)
            ->field('a.nickname,cal.*')
            ->find();
        $this->result($list,'操作成功',1);
    }


}